<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Config extends Backend
{
    public function __construct()
    {
        parent::__construct();

        $this->ConfigModel = model('Config');
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $title = '配置列表';

        // 查询数据
        $ConfigList = $this->ConfigModel->paginate(1);
        // 编号 currentPage 当前页 listRows 每页要显示多少条数据
        $sun = ($ConfigList->currentPage() - 1) * $ConfigList->listRows();

        // 赋值
        $this->assign([
            'title' => $title,
            'ConfigList' => $ConfigList,
            'sun' => $sun
        ]);
        // 输出视图
        return $this->fetch();
    }
    // 新增
    public function add()
    {
        $title = '添加配置';

        if($this->request->isPost())
        {
            // 接收所有参数
            $data = $this->request->param();

            // 插入数据库的数组
            $ConfigData = [
                'title' => $data['title'],
                'key' => $data['key'],
                'type' => $data['type']
            ];

            if($data['type'] == 'text')
            {
                $ConfigData['value'] = $data['value'];
            }elseif ($data['type'] == 'file') {
                $file = upload('file','uploads/admin');

                if($file === FALSE)
                {
                    $this->error('上传失败');
                    exit;
                }

                $ConfigData['value'] = $file;
            }

            $res = $this->ConfigModel->validate('common/Config')->save($ConfigData);

            if($res === FALSE)
            {
                $this->error($this->ConfigModel->getError());
                exit;
            }else{
                $this->success('添加成功',url('admin/config/index'));
                exit;
            }
        }
        $this->assign([
            'title' => $title
        ]);

        return $this->fetch();
    }


    /**
     * 编辑
     */
    public function edit()
    {
        $title = '编辑配置';

        $id = $this->request->param('id', 0);

        $data = $this->ConfigModel->find($id);
        // var_dump($id);
        // exit;
        if ($this->request->isPost()) {

            $title = $this->request->param('title', '');
            $value = $this->request->param('value', '');
            $type = $this->request->param('type', '');
            $key = $this->request->param('key', '');

            $res = [
                'id' => $id,
                'key' => $key,
                'title' =>  $title,
                'type' => $type
            ];

            //说明配置的类型是文本
            if ($type === "text") {

                $res['value'] = $value;
            } else if ($type == "file") {

                if ($_FILES["file"]["size"] > 0) {
                    //说明配置是文件
                    $result = upload('file');

                    if ($result === FALSE) {
                        $this->error('上传文件失败');
                        exit;
                    }

                    //组装数据
                    $res['value'] = '/uploads/' . $result;
                }
            }

            //更新数据库
            $result = $this->ConfigModel->isUpdate(true)->save($res);

            if ($result === FALSE) {
                $this->error($this->ConfigModel->getError());
                exit;
            } else {
                //如果是有上传新文件，需要先把旧文件删除
                //判断是否有文件上传
                if ($res['type'] == "file" && $_FILES['file']['size'] > 0) {
                    $old = ltrim($data['value'], "/");
                    @is_file($old) && @unlink($old);
                }
                $this->success('编辑配置成功', url('admin/config/index'));
                exit;
            }
        };
        $this->assign([
            'title' => $title,
            'info' => $data
        ]);

        return $this->fetch();
    }

   
    // 删除
    public function delete()
    {
        if ($this->request->isAjax()) {
            // 接收删除操作的状态 0 单条 1 多条
            // $state = $this->request->param('state');

            $ids = $this->request->param('id', '');

            // $ids = !empty($ids) ? rtrim($ids,',') : '';

            $idArr = explode(',', $ids);

            $idArr = array_filter($idArr);

            // 封装返回信息的数组
            $result = [
                'code' => 0,
                'msg' => '未知信息',
            ];

            if (empty($idArr)) {
                $result['msg'] = '请选择要删除的配置';
                return json($result);
            }

            $res = $this->ConfigModel->whereIn('id', $idArr)->delete();

            if ($res === FALSE) {
                $result['msg'] = '删除失败';
                return json($result);
            } else {
                $result['code'] = 1;
                $result['msg'] = '删除成功';
                return json($result);
            }
        }
    }

    // 单个删除
    public function del()
    {
        if ($this->request->isAjax()) {
            // 接收删除操作的状态 0 单条 1 多条
            // $state = $this->request->param('state');

            $ids = $this->request->param('id', '');

            // $ids = !empty($ids) ? rtrim($ids,',') : '';

            $idArr = explode(',', $ids);

            $idArr = array_filter($idArr);

            // 封装返回信息的数组
            $result = [
                'code' => 0,
                'msg' => '未知信息',
            ];

            if (!empty($idArr)) {
                $result['msg'] = '请选择要删除的配置';
                return json($result);
            }

            $res = $this->ConfigModel->whereIn('id', $idArr)->delete();

            if ($res === FALSE) {
                $result['msg'] = '删除失败';
                return json($result);
            } else {
                $result['code'] = 1;
                $result['msg'] = '删除成功';
                return json($result);
            }
        }
    }
}
